from braces.views import LoginRequiredMixin
from django.conf import settings
from django.contrib.auth import get_user_model, REDIRECT_FIELD_NAME, authenticate
from django.contrib.auth.views import login
from django.core.urlresolvers import reverse_lazy, reverse
from django.shortcuts import resolve_url, redirect, render_to_response
from django.views.decorators.cache import never_cache
from django.views.decorators.csrf import csrf_protect
from django.views.decorators.debug import sensitive_post_parameters
from django.views.generic import UpdateView
from accounts.forms import LoginForm, PasswordForm

max_cookies_age = 7 * 24 * 60 * 60  # 7 day


@sensitive_post_parameters()
@csrf_protect
@never_cache
def account_login(request, template_name='login.html',
                  redirect_field_name=REDIRECT_FIELD_NAME,
                  authentication_form=LoginForm,
                  current_app=None, extra_context=None):
    if request.method == 'GET':
        return login(request, template_name, redirect_field_name, authentication_form, current_app, extra_context)
    else:
        form = authentication_form(request, data=request.POST)
        if form.is_valid():
            remember = True if form.cleaned_data['remember'] == 'True' else False
            user = authenticate(username=form.cleaned_data['username'], password=form.cleaned_data['password'])
            if user is not None:
                response = redirect(reverse('admin_list'), arg=[])
                if remember:
                    response.set_cookie('username', form.cleaned_data['username'], max_age=max_cookies_age)
                    response.set_cookie('password', form.cleaned_data['password'], max_age=max_cookies_age)
                    response.set_cookie('remember', remember, max_age=max_cookies_age)
                else:
                    response.delete_cookie('username')
                    response.delete_cookie('password')
                    response.delete_cookie('remember')
                return response
            else:
                return login(request, template_name, redirect_field_name, authentication_form, current_app,
                             extra_context)
        else:
            return login(request, template_name, redirect_field_name, authentication_form, current_app, extra_context)


class PasswordUpdate(UpdateView):
    template_name = 'accounts/password_update.html'
    form_class = PasswordForm
    model = get_user_model()

    def get_success_url(self):
        return resolve_url('agent_create')
